package com.guanyong.files.handles;



import com.guanyong.utils.Encrypt.Base64Utils;
import com.guanyong.utils.LogHelper.LogHelper;
import com.guanyong.utils.UniqueID.DBObjectID;
import com.guanyong.utils.NetUtils.UploadFileUtil;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Eric.Zhang on 2017/1/4.
 */
//@Configuration
//@Component
//@PropertySources("classpath:application.properties")
public class UploadSaveHandle {



    // 上传文件的目录
//   @Value("${sfl.upload.insite}")
    //   @Value("#{systemProperties['sfl.upload.insite']}")

    @Value("${sfl.fileupload.insite}")
    private String insite;
    // 上传文件的目录
//    @Value("${sfl.upload.path}")
//    @Value("#{systemProperties['sfl.upload.path']}")
    @Value("${sfl.fileupload.path}")
    private String _uploadPath;// "/Images/upload/photo";
    // 临时文件目录
//    @Value("${sfl.upload.temppath}")
    @Value("${sfl.fileupload.temppath}")
    private String _tempPath;//"/Images/upload/photo/temp";

    @Value("${sfl.fileupload.root}")
    private String _uploadRoot; //"/Images/upload/

    @Value("${sfl.fileupload.remoteUploadUrl}")
    //远程目录
    private String remoteUploadUrl; //"/Images/upload/

    String uploadPath;
    String tempPath;
    String uploadRoot;
    File tempPathFile;


    public void init() throws ServletException, IOException {

        if (insite.equals("true")) {
            String webDir=this.getClass().getResource("/").getPath()+"/static";
            uploadPath= (webDir+_uploadPath).replace("//","/");
            tempPath= (webDir+_tempPath).replace("//","/");
            uploadRoot=(webDir+_uploadRoot).replace("//","/");
//            uploadPath= this.getClass().getResource(_uploadPath).getPath();
//            tempPath= this.getClass().getResource(_tempPath).getPath();
//            uploadRoot= this.getClass().getResource(_uploadRoot).getPath();


//            uploadPath = request.getSession().getServletContext().getRealPath(_uploadPath);
//            tempPath = request.getSession().getServletContext().getRealPath(_tempPath);
//            uploadRoot= request.getSession().getServletContext().getRealPath(_uploadRoot);
        }else{
            tempPath = _tempPath;
            uploadPath = _uploadPath;
        }
        System.out.print(uploadPath);
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        File tempPathFile = new File(tempPath);
        if (!tempPathFile.exists()) {
            tempPathFile.mkdirs();
        }
    }

    public String SaveSingleFile(HttpServletRequest request) throws ServletException, IOException {

        try {
            init();
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Set factory constraints
            factory.setSizeThreshold(1024 * 1024); // 设置缓冲区大小，这里是1mb
            factory.setRepository(tempPathFile);// 设置缓冲区目录

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            // Set overall request size constraint
            upload.setSizeMax(4194304); // 设置最大文件尺寸，这里是4MB

            List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
            Iterator<FileItem> i = items.iterator();
            if (i.hasNext()) {//只接收一个文件
                FileItem fi = (FileItem) i.next();
                String fileName = fi.getName();
                if (fileName != null) {
                    File fullFile = new File(fi.getName());
                    String savefilename = new DBObjectID().toString() + ".jpg";
                    File savedFile = new File(uploadPath, savefilename);
                    fi.write(savedFile);
                    return (_uploadPath + "/" + savefilename).replace("//", "/");
                }
            }
            System.out.print("upload succeed");
        } catch (Exception e) {
            // 可以跳转出错页面
            LogHelper.logger().error("后台用户上传头像失败：" + e.getMessage());
        }
        return "";
    }


    public String SaveFileByMultiFlie(MultipartFile file, HttpServletRequest request, String uploadEnum)
            throws ServletException, IOException {

        init();
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(1024 * 1024); // 设置缓冲区大小，这里是1mb
        factory.setRepository(tempPathFile);// 设置缓冲区目录

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        if (!file.isEmpty() && file.getSize() > 0) {
            String fullFileName = file.getOriginalFilename();
            //获取扩展名称
            String suffixName = fullFileName.substring(fullFileName.lastIndexOf("."));
            String uploadPath = uploadRoot + uploadEnum+"/";
            String newFileName = new DBObjectID().toString() + suffixName;
            String newFilePath = uploadPath + File.separator + newFileName;
            try {
                File dest = new File(newFilePath);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                try {
                    file.transferTo(dest);
                    return _uploadRoot+ uploadEnum+"/" + newFileName;
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                // 可以跳转出错页面
                LogHelper.logger().error("后台用户上传头像失败：" + e.getMessage());
                return "";
            }
        } else {
            //没有文件\
            return "";
        }

        return "";
    }

    public String SaveFileByRemoteServer( MultipartFile file, HttpServletRequest request, String
            uploadEnum)throws ServletException, IOException{
        init();
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(1024 * 1024); // 设置缓冲区大小，这里是1mb
        factory.setRepository(tempPathFile);// 设置缓冲区目录

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        if (!file.isEmpty() && file.getSize() > 0) {
            String fullFileName = file.getOriginalFilename();
            //获取扩展名称
            String suffixName = fullFileName.substring(fullFileName.lastIndexOf("."));

            String uploadPath = uploadRoot + uploadEnum.toString();
            String newFileName = new DBObjectID().toString() + suffixName;
            String newFilePath = uploadPath + File.separator + newFileName;
            try {
                Map<String, String> textMap = new HashMap<String, String>();
                textMap.put("uploadEnum", uploadEnum.toString());
                textMap.put("uploadKey", "7h(sllG.");
                String result =  UploadFileUtil.formUpload(remoteUploadUrl,textMap,"file",fullFileName,file.getInputStream(),file.getContentType());
                return  result;

            } catch (Exception e) {
                // 可以跳转出错页面
                LogHelper.logger().error("后台用户上传头像失败：" + e.getMessage());
                return "";
            }
        } else {
            //没有文件\
            return "";
        }

    }
    public String SaveStringFile(String Data, HttpServletRequest request) throws Exception {
        try {
            init();
            byte[] filedata = Base64Utils.decode(Data);
            String filename = new DBObjectID().toString() + ".jpg";
            String savefilename = uploadPath + "/" + filename;
            File file = new File(savefilename);
            FileOutputStream fos = new FileOutputStream(file);

            //用FileOutputStream 的write方法写入字节数组
            fos.write(filedata);
            System.out.println("写入成功");

            //为了节省IO流的开销，需要关闭
            fos.close();

            return (_uploadPath + "/" + filename).replace("//", "/");
        } catch (Exception ex) {
            LogHelper.logger().error("后台用户上传头像失败SaveStringFile：" + ex.getMessage());
        }
        return "";

    }
}
